from typing import Dict, List


class SystemStatisticsManager:
    """
    系统信息统计(数据库查询)
    """

    _business_data = None
    _game_status_statistics = None
    _game_timeline = None
    _random_vm = None

    def get_business_data(self) -> Dict:

        from app.models import (
            courseModel,
            ctfModel,
            questionModel,
            rangeModel,
            userModel,
        )

        if not self._business_data:
            self._business_data = {
                "ctf_count": ctfModel.Ctf.query.count(),  # ctf数量
                "ctf_question_count": questionModel.CtfQuestion.query.count(),  # ctf题数量
                "range_count": rangeModel.Range.query.count(),  # 仿真场景数量
                "courseware_count": courseModel.Course.query.count(),  # 课件数量
                "user_count": userModel.User.query.filter_by(role_id=0).count(),  # 学生数量
            }
        return self._business_data

    def get_game_status_statistics(self) -> Dict:
        """
        竞技比赛状态统计
        """
        from sqlalchemy.sql import func

        from app.models import ctfModel

        data = (
            ctfModel.Ctf.query.with_entities(
                func.count(ctfModel.Ctf.id), ctfModel.Ctf.status
            )
            .group_by(ctfModel.Ctf.status)
            .all()
        )

        if not self._game_status_statistics:
            self._game_status_statistics = {"close": 0, "starting": 0, "finish": 0}
            for item in data:
                if item[1] == 0:
                    self._game_status_statistics["close"] = item[0]
                elif item[1] == 1:
                    self._game_status_statistics["starting"] = item[0]
                elif item[1] == 2:
                    self._game_status_statistics["finish"] = item[0]
        return self._game_status_statistics

    def get_game_timeline(self) -> Dict:
        """
        比赛时间轴
        """
        from sqlalchemy.sql import func

        from app.models import ctfModel

        if not self._game_timeline:
            data = (
                ctfModel.Ctf.query.with_entities(
                    func.count(ctfModel.Ctf.id).label("countID"),
                    func.FROM_UNIXTIME(ctfModel.Ctf.start_date, "%Y-%m-%d").label(
                        "weeks"
                    ),
                )
                .group_by("weeks")
                .all()
            )

            self._game_timeline = {}
            for item in data:
                self._game_timeline[item[1]] = item[0]

        return self._game_timeline

    def get_random_vm(self, user_id: int = None, limit: int = 10) -> List:
        """
        随机获取10个虚拟机
        """
        from app.models import rangeModel

        filters = []
        if user_id:
            filters.append(rangeModel.RangeVm.user_id == user_id)

        data = rangeModel.RangeVm.query.filter(*filters).limit(limit).all()

        self._random_vm = []
        for rang_vm in data:
            self._random_vm.append(
                {
                    "vm_name": rang_vm.vm_name,
                    "create_time": rang_vm.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "type": rang_vm.type,
                }
            )
        return self._random_vm
